const express = require('express');
const fs = require('fs');
const router = express.Router();
const usersFilePath = 'users.json'; // 用户数据文件的路径

// 获取用户列表
router.get('/users', (req, res) => {
  fs.readFile(usersFilePath, (err, data) => {
    if (err) {
      return res.status(500).json({ message: 'Error reading users.json' });
    }
    res.json(JSON.parse(data));
  });
});

// 注册新用户
router.post('/register', (req, res) => {
  const { name, password } = req.body;
  fs.readFile(usersFilePath, (err, data) => {
    if (err) {
      return res.status(500).json({ message: 'Error reading users.json' });
    }
    const users = JSON.parse(data);
    const existingUser = users.find(user => user.name === name);
    if (existingUser) {
      return res.status(409).json({ message: 'Username already exists' });
    }
    users.push({ name, password });
    fs.writeFile(usersFilePath, JSON.stringify(users, null, 2), (err) => {
      if (err) {
        return res.status(500).json({ message: 'Error writing to users.json' });
      }
      res.json({ message: 'User registered successfully' });
    });
  });
});

// 用户登录
router.post('/login', (req, res) => {
  const { name, password } = req.body;
  fs.readFile(usersFilePath, (err, data) => {
    if (err) {
      return res.status(500).json({ message: 'Error reading users.json' });
    }
    const users = JSON.parse(data);
    const user = users.find(user => user.name === name && user.password === password);
    if (user) {
      res.json({ message: 'Login successful', username: user.name });
    } else {
      res.status(401).json({ message: 'Invalid username or password' });
    }
  });
});

module.exports = router;